package cn.xsly.org.service.impl;

import cn.xsly.basic.service.impl.BaseServiceImpl;
import cn.xsly.basic.util.Md5Utils;
import cn.xsly.basic.util.StrUtils;
import cn.xsly.org.mapper.EmployeeMapper;
import cn.xsly.org.service.IEmployeeService;
import cn.xsly.org.domain.Employee;
import cn.xsly.user.domain.Logininfo;
import cn.xsly.user.mapper.LogininfoMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 业务实现类：员工
 */
@Service
public class EmployeeServiceImpl extends BaseServiceImpl<Employee> implements IEmployeeService {

@Autowired
private EmployeeMapper employeeMapper;
@Autowired
private LogininfoMapper logininfoMapper;
    //修改员工表的同时还需要把登录表的信息也修改（密码和盐值）
    @Override
    public void add(Employee employee){
        String salt = StrUtils.getComplexRandomString(32);
        String byMd5 = Md5Utils.encrypByMd5(employee.getPassword() + salt);
        employee.setSalt(salt);
        employee.setPassword(byMd5);
        Logininfo logininfo=employee2Logininfo(employee);
        logininfoMapper.add(logininfo);
        employee.setLogininfoId(logininfo.getId());
        super.add(employee);
        //添加员工的同时加入员工角色
        employeeMapper.addEmployeeRole(employee);
    }
    //员工需要转为登录信息保存起来，
    private Logininfo employee2Logininfo(Employee employee) {
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(employee,logininfo);
        logininfo.setType(0);
        return logininfo;
    }
    //查出员工里面的登录id，根据登录id去删该员工登录信息
    @Override
    public void delete(Long id){
        Employee employee = employeeMapper.findById(id);
        logininfoMapper.delete(employee.getLogininfoId());
        super.delete(id);
        //添加员工的同时加入员工角色
        employeeMapper.delEmployeeRole(id);
    }
    //根据员工查出登录id，在修改登录信息表，最后修改员工表
    @Override
    public void update(Employee employee){
        String salt = StrUtils.getComplexRandomString(32);
        String byMd5 = Md5Utils.encrypByMd5(employee.getPassword() + salt);
        employee.setSalt(salt);
        employee.setPassword(byMd5);
        Logininfo logininfo=employee2Logininfo(employee);
        Long logininfoId = employeeMapper.findById(employee.getId()).getLogininfoId();
        logininfo.setId(logininfoId);
        logininfoMapper.update(logininfo);
        super.update(employee);
        //对角色表就先删后加
        employeeMapper.delEmployeeRole(employee.getId());
        employeeMapper.addEmployeeRole(employee);
    }
}
